<?php
/**
 * Created by PhpStorm.
 * User: luoqinghui
 * Date: 2020/7/24
 * Time: 上午17:40
 */

namespace App\Http\Controllers\Api\Device;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 设备管理
 * Class HomeController
 * @package App\Http\Controllers\Api\Home
 */
class DeviceController extends Controller
{
    /**
     * 我的设备列表
     */
    public function deviceIndex(Request $request){
        $size = $request->input('size',15);
        $brand_name = $request->input('brand_name','');
        $user_id = $this->getLoginUser()->id;
//        $user_id = 16;
        //查询
        $result = DB::table('device AS D')->select(['F.id','F.brand_name','F.facory_name','F.img','F.device_type','D.device_code'])
            ->leftJoin('facory AS F','D.facory_id','=','F.id')
            ->where('D.bundled_user_id',$user_id)->where('D.status',1);
        if ( !empty($brand_name) ) {
            $result = $result->where('brand_name','like','%'.$brand_name.'%');
        }
        $result = $result->paginate($size);
        foreach ( $result as $key => $value ) {
            if ( !empty($result->items()[$key]->img) ) {
                $result->items()[$key]->img = env('APP_DOMAIN').$result->items()[$key]->img;
            }
        }
        return response()->pagination($result);
    }

    /**
     * 绑定设备
     * 用户拿到设备后做蓝牙绑定
     */
    public function userBundled(Request $request){
        $user_id = $this->getLoginUser()->id;
//        $user_id = 1;
        $device_code = $request->input('device_code');
        if ( empty($device_code) ) return response()->error("PARAM_EMPTY");
        //判断设备是否已绑定
        $deviceData = DB::table('device')->select(['id','bundled_user_id','is_bundled'])->where('device_code',$device_code)->first();
        if ( empty($deviceData) ) return response()->error("PARAM_ERROR");
        if ( $deviceData->is_bundled == 1 ) return response()->error("DEVICE_BUNDLED");
        //更新绑定关系数据
        $result = DB::table('device')->where('device_code',$device_code)->update(['is_bundled'=>1,'bundled_user_id'=>$user_id,'bundled_date'=>date('Y-m-d H:i:s',time())]);
        if ( empty($result) ) return response()->error("ERROR_BUNDLED");
        return response()->success(null);
    }
}
























